﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Landscape.Business;
using Landscape.Business.Entities;
using Landscape.Business.FNH;
using Landscape.Business.FNH.Activities;
using Telerik.Web.UI;

namespace Landscape.WebApp.Internal.Operations
{
    public partial class OpMaster : System.Web.UI.MasterPage
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            //Is User loggedin
            if (Session["ACTIVE_USER"] != null)
            {
                //If logged in user is external user
                if (!((Landscape.WebApp.UIBizObjects.ActiveUser)Session["ACTIVE_USER"]).IsADUser)
                {
                    Response.Redirect("~/Redirect.aspx");
                }
            }
            else
            {
                Response.Redirect("~/Logout.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.title.Text = @"  " + (this.Page as BasePage).PageTitle;

            //Navigation items are the one to be displatied in the navigation panel
            if (Cache["NAV_ITEMS"] == null)
            {
                if (((Landscape.WebApp.UIBizObjects.ActiveUser)Session["ACTIVE_USER"]).IsSysAdmin)
                {//If the user is system admin then load all
                    using (var nhSession = NHSessionManager.GetManager().GetSession())
                    {
                        AdminActivities adminActs = new AdminActivities(nhSession);
                        var modules = adminActs.GetSystemAdminModules("INTERNAL");

                        if (modules != null)
                        {
                            List<Landscape.WebApp.UIBizObjects.NavItem> navItems = new List<UIBizObjects.NavItem>();
                            foreach (var item in modules)
                            {
                                navItems.Add(new UIBizObjects.NavItem() { SequenceNo = item.IndexNumber, Title = item.Name, URL = item.Url, ID = item.ID, ItemType = item.Location, ParentID = item.ParentModule });
                            }
                            Cache.Add("NAV_ITEMS", navItems, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
                        }
                    }
                }
                else
                {//Load only those what user had.

                }
            }
            loadNavigationPanel();
            
            this.lblUserName.Text = (this.Page as BasePage).CurrentUser.FullName;

            if (!IsPostBack && this.Page is BasePage)
            {
                loadVessels();
                this.hfUserCode.Value = (this.Page as BasePage).CurrentUser.UserID.ToString();

                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    AdminActivities adminActs = new AdminActivities(nhSession);
                    List<SystemModulePrivilege> privileges = adminActs.GetUserPrivilegesFor((this.Page as BasePage).PageID, (this.Page as BasePage).CurrentUser.UserID);
                    string privColString = privileges.Aggregate(string.Empty, (str, next) => str += next.Name + ",");
                    this.hfModulePrivileges.Value = privColString;
                }
            }
        }

        private void loadNavigationPanel()
        {
            List<UIBizObjects.NavItem> navItems = (List<UIBizObjects.NavItem>)Cache["NAV_ITEMS"];
            //Clear all the existing items
            this.rpbNavigation.Items.Clear();

            //Add the root items
            if (navItems != null)
            {
                foreach (var item in navItems.Where(exp => exp.ParentID == null).OrderBy(exp => exp.SequenceNo))
                {
                    var panelItem = new RadPanelItem();
                    panelItem.Value = item.ID.ToString();
                    panelItem.Text = item.Title;
                    panelItem.NavigateUrl = item.URL;

                    loadChildItemsToParent(ref panelItem, navItems);
                    this.rpbNavigation.Items.Add(panelItem);
                }
            }
        }

        private void loadChildItemsToParent(ref RadPanelItem pParentItem, List<UIBizObjects.NavItem> pNavItems)
        {
            var parentID = Guid.Parse(pParentItem.Value);

            foreach (var item in pNavItems.Where(exp => exp.ParentID == parentID).OrderBy(exp => exp.SequenceNo))
            {
                var panelItem = new RadPanelItem();
                panelItem.Value = item.ID.ToString();
                panelItem.Text = item.Title;
                panelItem.NavigateUrl = item.URL;

                loadChildItemsToParent(ref panelItem, pNavItems);
                pParentItem.Items.Add(panelItem);
            }
        }

        private void loadVessels()
        {
            if (Cache["VESSELS"] == null)
            {
                AdminActivities adminActs = new AdminActivities();
                var vessels = adminActs.GetVesselsByName(string.Empty, 0, -1);

                vessels.Insert(0, new Vessel() { ID = new Guid(), Name = "-Select-" });

                this.rcbVessels.DataSource = vessels;
                this.rcbVessels.DataBind();

                //this.rcbVessels.Items.Insert(0, new RadComboBoxItem("-Select-", "-Select-"));

                Cache.Add("NAV_ITEMS", vessels, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
            }
        }

        protected void rcbVessels_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            MaintenanceActivities maintActs = new MaintenanceActivities();
            if (e.Value != (new Guid()).ToString())
            {
                this.rtvSysterms.DataSource = maintActs.GetVesselSystems(Guid.Parse(e.Value)).Select((func) => new { func.ID, func.Product.Name, ParentID = (func.Parent != null ? new Nullable<Guid>(func.Parent.ID) : new Nullable<Guid>()) });
                this.rtvSysterms.DataBind();

                if (Session["ACTIV_VESSEL"] != null)
                {
                    Session["ACTIV_VESSEL"] = e.Value;                    
                }
                else
                {
                    Session.Add("ACTIV_VESSEL", e.Value);
                }
            }
            else
            {
                this.rtvSysterms.Nodes.Clear();

                if (Session["ACTIV_VESSEL"] != null)
                {
                    Session.Remove("ACTIV_VESSEL");
                }

                if (Session["ACTIV_SYSTEM"] != null)
                {
                    Session.Remove("ACTIV_SYSTEM");
                }
            }
        }

        protected void rtvSysterms_NodeDataBound(object sender, RadTreeNodeEventArgs e)
        {
            e.Node.Text = ((dynamic)e.Node.DataItem).Name;            
        }

        protected void rtvSysterms_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            if (Session["ACTIV_SYSTEM"] != null)
            {
                Session["ACTIV_SYSTEM"] = e.Node.Value;
            }
            else
            {
                Session.Add("ACTIV_SYSTEM", e.Node.Value);
            }
        }       
    }
}